import java.awt.*;
import java.util.List;
import java.util.*;

public class Game1 {

    public static void main(String[] args) {
        int categorys = 20;
        int dispelGroupNum = 30;
        int levelSize = 10;
        List<FullList<Point>> cardMap = initTempCardMap(dispelGroupNum, levelSize);
        int[] randomCards = generatorRandomCards(dispelGroupNum, categorys);
        System.out.println(Arrays.toString(randomCards));
        mappingRandomCardsToCardMap(cardMap, randomCards);
        List<Node> coverageRelations = new ArrayList<>();
        List<Node> viewCard = new ArrayList<>();
        generateConverageRelations(cardMap, coverageRelations, viewCard);
        play(coverageRelations, viewCard);

    }

    private static void play(List<Node> coverageRelations, List<Node> viewCard) {
        FullList<Node> playStorage = new FullList<>(7);
        Scanner scanner = new Scanner(System.in);
        for (; ; ) {
            show(viewCard, playStorage, coverageRelations);
            String line = scanner.nextLine();
            try {
                String[] commonds = line.split(",");
                Node commondNode = null;
                commondNode = moveViewCardToStorage(viewCard, playStorage, commonds, commondNode);
                if (!playStorage.isNotFull()) {
                    System.out.println("Game Over");
                    break;
                }
                coverageCardToViewCard(coverageRelations, viewCard, commondNode);
                if (viewCard.size() == 0) {
                    System.out.println("恭喜挑战成功");
                    break;
                }
            } catch (Exception e) {
                System.out.println("输入不合法");
            }
        }
    }

    private static Node moveViewCardToStorage(List<Node> viewCard, FullList<Node> playStorage, String[] commonds, Node commondNode) {
        for (Node node : viewCard) {
            if (node.level == Integer.parseInt(commonds[0]) && node.index == Integer.parseInt(commonds[1])) {
                playStorage.add(node);
                commondNode = node;
            }
        }
        if (commondNode == null) {
            System.out.println("输入的元素不存在");
        } else {
            viewCard.remove(commondNode);
        }
        List<Node> sameCategoryList = new ArrayList<>();
        for (Object obj : playStorage) {
            Node node = (Node) obj;
            if (node.point.category == commondNode.point.category) {
                sameCategoryList.add(node);
            }
        }
        if (sameCategoryList.size() == 3) {
            for (Node node : sameCategoryList) {
                playStorage.remove(node);
            }
        }
        return commondNode;
    }

    private static void coverageCardToViewCard(List<Node> coverageRelations, List<Node> viewCard, Node commondNode) {
        List<Node> tempCoverageNodes = new ArrayList<>();
        for (Node node : coverageRelations) {
            if (node.nodeList.size() > 0) {
                Node tempNode = null;

                for (Node childNode : node.nodeList) {
                    if (childNode.level == commondNode.level && childNode.index == commondNode.index) {
                        tempNode = childNode;
                    }
                }
                if (tempNode != null) {
                    node.nodeList.remove(tempNode);
                }
                if (node.nodeList.size() == 0) {
                    tempCoverageNodes.add(node);
                }
            }
        }
        if (tempCoverageNodes.size() > 0) {
            for (Node node : tempCoverageNodes) {
                coverageRelations.remove(node);
                viewCard.add(node);
            }
        }
    }

    private static void show(List<Node> viewCards, FullList<Node> playStorage, List<Node> coverageRelations) {
        System.out.println("\n隐藏部分--------");
        for (Node node : coverageRelations) {
            System.out.print(node.level + "," + node.index + "[" + node.point.category + "]");
            if(node.nodeList.size()>0){
                System.out.print("\t{");
                for (Node coverNode:node.nodeList){
                    System.out.print(coverNode.level+","+coverNode.index+"[" + coverNode.point.category + "]\t");
                }
                System.out.print("}\n");
            }
        }
        System.out.println("\n视野地图--------");
        for (Node node : viewCards) {
            System.out.print(node.level + "," + node.index + "[" + node.point.category + "]\t");
        }
        System.out.println("\n缓存区地图--------");
        for (Object obj : playStorage) {
            Node node = (Node) obj;
            System.out.print(node.level + "," + node.index + "[" + node.point.category + "]\t");
        }
        System.out.println();
    }

    /**
     * 定义覆盖关系
     *
     * @param cardMap
     * @return
     */
    private static void generateConverageRelations(List<FullList<Point>> cardMap, List<Node> coverageRelations, List<Node> viewCard) {
        //每一层
        for (int i = 0; i < cardMap.size(); i++) {
            FullList<Point> eachLavel = cardMap.get(i);
            //当前层的任意一次是否对当前层的任意元素有覆盖关系
            for (int j = 0; j < eachLavel.size(); j++) {
                Point point = (Point) eachLavel.get(j);
                Node currentNode = new Node();
                currentNode.level = i;
                currentNode.index = j;
                currentNode.point = point;
                currentNode.nodeList = findContainsPoint(cardMap, i + 1, point);
                if (currentNode.nodeList.size() > 0) {
                    coverageRelations.add(currentNode);
                } else {
                    viewCard.add(currentNode);
                }
            }
        }
    }

    private static List<Node> findContainsPoint(List<FullList<Point>> cardMap, int startIndex, Point point) {
        List<Node> containsPoint = new ArrayList<>();
        for (int i = startIndex; i < cardMap.size(); i++) {
            FullList<Point> eachLavel = cardMap.get(i);
            //当前层的任意一次是否对当前层的任意元素有覆盖关系
            for (int j = 0; j < eachLavel.size(); j++) {
                Point targetPoint = (Point) eachLavel.get(j);
                if (point.containsPoint(targetPoint)) {
                    Node targetNode = new Node();
                    targetNode.level = i;
                    targetNode.index = j;
                    targetNode.point = targetPoint;
                    containsPoint.add(targetNode);
                }
            }
        }
        return containsPoint;
    }

    /**
     * 姜随机卡片填充到卡片地图中
     *
     * @param cardMap
     * @param randomCards
     */
    private static void mappingRandomCardsToCardMap(List<FullList<Point>> cardMap, int[] randomCards) {
        //将随机卡片内容填充到地图到每个元素
        int cardLevel = 0;
        for (int key : randomCards) {
            FullList<Point> eachLevelCards = cardMap.get(cardLevel);
            Point point = new Point();
            point.category = key;
            if (eachLevelCards.isNotFull()) {
                eachLevelCards.add(point);
            } else {
                cardLevel++;
                eachLevelCards = cardMap.get(cardLevel);
                eachLevelCards.add(point);
            }
        }

        //为地图的每个元素添加x，y，长度坐标
        //初始固定X
        int fixedX = 20;
        //初始固定Y
        int fixedY = 20;
        //卡片长度
        int cardLength = 20;
        Random random = new Random();
        for (List<Point> list : cardMap) {
            // 横向限制个数
            int splitLimitCount = 1 + random.nextInt(list.size() / 2);
            //随机X
            int randStepX = random.nextInt(3);
            //随机Y
            int randStepY = random.nextInt(3);
            //开始X = 固定x+随机x*10
            int startXIndex = fixedX + randStepX * 10;
            //开始Y = 固定y+随机Y*10
            int startYIndex = fixedY + randStepY * 10;
            for (int i = 0; i < list.size(); i++) {
                Point point = list.get(i);
                if (i % splitLimitCount == 0) {
                    startYIndex += 20;
                    startXIndex = fixedX + randStepX * 10;
                    System.out.println();
                } else {
                    startXIndex += 20;
                }
                point.x = startXIndex;
                point.y = startYIndex;
                point.length = cardLength;
                System.out.print("[" + point.x + "," + point.y + "]" + point.category + "\t");
            }
            System.out.println();
        }
    }


    /**
     * 生成随机卡片
     *
     * @param dispelGroupNum
     * @param totalCategory
     * @return
     */
    private static int[] generatorRandomCards(int dispelGroupNum, int totalCategory) {
        Random random = new Random();
        int[] totalCardNum = new int[dispelGroupNum * 3];
        for (int i = 0; i < dispelGroupNum; i++) {
            int catgory = random.nextInt(totalCategory);
            for (int j = 0; j < 3; j++) {
                for (; ; ) {
                    int index = random.nextInt(totalCardNum.length);
                    if (totalCardNum[index] == 0) {
                        totalCardNum[index] = catgory;
                        break;
                    }
                }
            }
        }
        return totalCardNum;
    }

    /**
     * 定义初始化地图
     *
     * @return
     */
    private static List<FullList<Point>> initTempCardMap(int dispelGroupNum, int levelSize) {
        int totalNum = dispelGroupNum * 3;
        List<FullList<Point>> cardMap = new ArrayList<>();
        //每个组的平均值
        int eachLeveAgaCount = totalNum / levelSize;
        Random random = new Random();
        /**
         * 平局值+小范围的波动值 波动值为0～(平均值/组)
         * 比如 消除组的数量为 9，总个数为9*3=27，分3个组。则每组的平均值为9，波动值为3
         */
        int seadRange = eachLeveAgaCount / levelSize;
        //剩余数量
        int leftCount = totalNum;
        for (int i = 0; i < levelSize; i++) {
            FullList<Point> level = null;
            if (i == levelSize - 1) {
                level = new FullList<>(leftCount);
            } else {
                level = new FullList<>(eachLeveAgaCount + (seadRange>0?random.nextInt(seadRange):0));
            }
            cardMap.add(level);
        }
        return cardMap;
    }

    static class FullList<T> extends ArrayList {
        int size;

        public FullList(int size) {
            this.size = size;
        }

        public boolean isNotFull() {
            return this.size() < this.size;
        }
    }

    /**
     * 覆盖关系
     */
    public static class Node {
        int level;
        Integer index;
        Point point;
        List<Node> nodeList = new ArrayList<>();
    }

    public static class Point {
        /**
         * 开始X节点
         */
        int x;
        /**
         * 开始Y节点
         */
        int y;
        int length;
        int category;

        public boolean containsPoint(Point point) {
            Rectangle re1 = new Rectangle(x, y, 20, 20);
            Rectangle re2 = new Rectangle(point.x, point.y, 20, 20);
            Rectangle intersection = re1.intersection(re2);// 交集
            if(!intersection.isEmpty()){
                return true;
            }else {
                return false;
            }
        }
    }
}
